package cn.sofwin.blog.servlet;

import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.service.UserService;
import cn.sofwin.blog.service.impl.UserServiceImpl;
import cn.sofwin.blog.utils.FileHelper;
import cn.sofwin.blog.utils.HttpHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 用户修改信息表
 * @author LetCode
 * @since 1.0
 *
 */
@WebServlet("/user/profile")
public class UserProfileServlet extends HttpServlet {
    //文件上传的路径（相对于站点根目录）
    private String uploadPath="/static/upload/";
    private UserService userService = UserServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("LOGIN_USER");
        req.setAttribute("user",user);
        req.getRequestDispatcher("/profile.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpHelper.charset(req);

        //磁盘文件工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //配置文件上传目录
        String folderPath= FileHelper.getWebRootPath(this.getClass())+uploadPath;
        File uploadFolder =new File(folderPath);
        factory.setRepository(uploadFolder);

        ServletFileUpload upload = new ServletFileUpload(factory);
        String nickname=req.getParameter("nickname");
        String password=req.getParameter("password");
        String avatar=req.getParameter("avatar");
        try {

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item:items){
                if (item.isFormField()){
                    //处理普通的表单元素
                    String name=item.getFieldName();
                    String value=item.getString("UTF-8");
                    switch (name){
                        case "nickname":
                            nickname=value;
                            break;
                        case "password":
                            password=value;
                            break;

                    }

                }else {
                    //处理文件上传
                    String fileName=item.getName();
                    //为了防止文件的重名，需要重新设置文件名
                    fileName=fileName.substring(fileName.lastIndexOf("."));
                    fileName=System.currentTimeMillis()+fileName;
                    //存储文件
                    item.write(new File(folderPath+fileName));
                    //设置头像访问路径
                    avatar=uploadPath+fileName;
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }



        User user = (User) req.getSession().getAttribute("LOGIN_USER");


        //更新用户资料
        userService.updateProfile(user,password,nickname,avatar);

        //用户可能修改了密码，用户重新登录
        //1.移除session中的用户对象
        req.getSession().removeAttribute("LOGIN_USER");
        //2.重定向到登录页面
        resp.sendRedirect("/user/login");
    }


}